//
//  YPSongController.m
//  WHISPER
//
//  Created by lanou3g on 15/12/23.
//  Copyright © 2015年 王艳苹. All rights reserved.
//

#import "YPSongController.h"
#import "YPNetWorking.h"
#import "YPMakeURL.h"
#import "YPSongTableCell.h"
#import "UIView+Extention.h"
#import "YPSongCollectionCell.h"
#import "YPCurrentModel.h"
#import "YPSongModel.h"
#import "YPMoretingModel.h"
#import "UIImageView+WebCache.h"
#import "RadioDetailListModel.h"
#import "LYRadioHelper.h"
static YPSongController *song = nil;
@interface YPSongController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate,UIWebViewDelegate,LYRadioHelperDelegate>
@property (nonatomic,strong) YPSongModel *currentModel;
@property (nonatomic,strong) NSMutableArray *allTingList;
@property (nonatomic,copy) NSString *currentWeb;
@property (nonatomic,assign) NSInteger currentIndex;
@property (nonatomic,strong) NSString *currentImage;
@property (nonatomic,strong) UIActivityIndicatorView *activityView;
@property (nonatomic,assign) BOOL flag;
@end

@implementation YPSongController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setSize];
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [leftButton setImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:UIControlStateNormal];
    [leftButton setFrame:CGRectMake(15, 10,30,30)];
    [leftButton addTarget:self action:@selector(leftAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:leftButton];
    [self.playBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-iconfontzanting"] forState:UIControlStateNormal];
    self.allTingList = _tempListArr;
    if (self.isComeHomePage) {
        _currentIndex = self.index;
        self.isComeHomePage = NO;
    }else{
        if (self.index == _currentIndex) {
            if ( [self.tingId isEqualToString:_currentModel.tingid]) {
                return;
            }else{
                _currentIndex = self.index;
                [self makeCurrentSongModelByIndex:_currentIndex];
            }
        }else{
            _currentIndex = self.index;
            [self makeCurrentSongModelByIndex:_currentIndex];
        }
    }
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [[UIApplication sharedApplication] becomeFirstResponder];
}
- (BOOL)canBecomeFirstResponder{
    return YES;
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [[UIApplication sharedApplication] resignFirstResponder];
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        switch (receivedEvent.subtype) {
            case UIEventSubtypeRemoteControlPause:
                [self playBtnAction:nil];
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                [self nextSongAction:nil];
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                [self preSongAction:nil];
                break;
            case UIEventSubtypeRemoteControlPlay:
                [self playBtnAction:nil];
                break;
            default:
                break;
        }
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.currentIndex = -1;
    self.mainScroll.delegate = self;
    self.listTableView.delegate = self;
    self.listTableView.dataSource = self;
    self.otherWorks.delegate = self;
    self.otherWorks.dataSource = self;
    self.webView.delegate = self;
//    [self setSize];
    [LYRadioHelper shareLYRadioHelper].delegate = self;
    [self.listTableView registerNib:[UINib nibWithNibName:@"YPSongTableCell" bundle:nil] forCellReuseIdentifier:@"YPSongTableCell"];
    [self.otherWorks registerNib:[UINib nibWithNibName:@"YPSongCollectionCell" bundle:nil]forCellWithReuseIdentifier:@"YPSongCollectionCell"];
    self.hostImage.layer.masksToBounds = YES;
    self.hostImage.layer.cornerRadius = 20;
    self.userImage.layer.masksToBounds = YES;
    self.userImage.layer.cornerRadius = 20;
    [self.preSong addTarget:self action:@selector(preSongAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.preSong setBackgroundImage:[UIImage imageNamed:@"iconfont-ttpodicon"] forState:UIControlStateNormal];
    [self.nextSong addTarget:self action:@selector(nextSongAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.nextSong setBackgroundImage:[UIImage imageNamed:@"iconfont-ttpodicon(1)"] forState:UIControlStateNormal];
    [self.playBtn addTarget:self action:@selector(playBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.timeLable.font = [UIFont systemFontOfSize:13];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateButton:) name:@"updateButton" object:nil];
}

- (void)setSize{
    self.songImageView.frame = CGRectMake(100 * ([UIScreen mainScreen].bounds.size.width / 375.0), 100 * ([UIScreen mainScreen].bounds.size.height / 667.0), 150, 150);
}
- (void)updateButton:(NSNotification*)sender{
    [self playBtnAction:nil];
}
- (void)makeCurentModelWith:(NSString*)tingId{
    [[YPNetWorking shareNetWorking] getDictWithURL:[YPMakeURL shareMakeURL].songURL dict:[[YPMakeURL shareMakeURL] makeSongDictWithSongID:tingId]success:^(NSDictionary *dic) {
        YPSongModel *song = [[YPSongModel alloc]init];
        [song setValuesForKeysWithDictionary:dic[@"data"]];
        song.playInfo = [[YPCurrentModel alloc]init];
        [song.playInfo setValuesForKeysWithDictionary:dic[@"data"][@"playInfo"]];
        song.playInfo.authorinfo = [[YPUser alloc]init];
        [song.playInfo.authorinfo setValuesForKeysWithDictionary:dic[@"data"][@"playInfo"][@"authorinfo"]];
        song.playInfo.userinfo = [[YPUser alloc]init];
        [song.playInfo.userinfo setValuesForKeysWithDictionary:dic[@"data"][@"playInfo"][@"userinfo"]];
        song.moreting = @[].mutableCopy;
        for (NSDictionary *moreDic in dic[@"data"][@"moreting"]) {
            YPMoretingModel *more = [[YPMoretingModel alloc]init];
            [more setValuesForKeysWithDictionary:moreDic];
            [song.moreting addObject:more];
        }
        self.currentModel = song;
        [self.songImageView sd_setImageWithURL:[NSURL URLWithString:self.currentModel.playInfo.imgUrl] placeholderImage:[UIImage imageNamed:@"16"]];
        self.titleLable.text = self.currentModel.playInfo.title;
        self.likeLable.text = [NSString stringWithFormat:@"%ld",(long)song.like];
        self.disLable.text = [NSString stringWithFormat:@"%ld",(long)song.comment];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.currentModel.playInfo.webview_url]];
        self.mainScroll.contentOffset = CGPointMake(self.view.width,0);
         NSInteger index = self.mainScroll.contentOffset.x / self.view.width;
        UIView *view = [self.view viewWithTag:index + 350];
        view.backgroundColor = [UIColor yellowColor];
        [self.webView loadRequest:request];
        self.webView.y = - 44;
        self.webView.hight = self.webView.hight + 88;
        [[LYRadioHelper shareLYRadioHelper] playStringWithUrl:_currentModel.playInfo.musicUrl];
        if ([YPSongController shareSongController].block) {
            [YPSongController shareSongController].block(_allTingList,self.currentIndex);
        }
    } fail:^(NSError *err) {
        NSLog(@"%@",err);
    }];
}

- (void)RadioPlayEndWith:(LYRadioHelper *)lyradioHelper{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"HomePageUI" object:nil];
    [self nextSongAction:nil];
}

- (void)playerTime:(float)time LYRadiohelper:(LYRadioHelper *)lyRadioHelper{
    int timeM =  (int)time / 60;//分
    int timeS = (int)time % 60;//秒
    self.timeLable.text = [NSString stringWithFormat:@"%02d:%02d",timeM,timeS];
}

- (void)preSongAction:(UIButton*)sender{
    _currentIndex--;
    if (_currentIndex == -1) {
        _currentIndex = self.allTingList.count - 1;
    }
    [self makeCurrentSongModelByIndex:_currentIndex];
}

- (void)nextSongAction:(UIButton*)sender{
    _currentIndex++;
    if (_currentIndex == self.allTingList.count) {
        _currentIndex = 0;
    }

    [self makeCurrentSongModelByIndex:self.currentIndex];
}

- (void)playBtnAction:(UIButton*)sender{
    self.flag = !self.flag;
    if (self.flag) {
        [sender setBackgroundImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
    }else{
        [sender setBackgroundImage:[UIImage imageNamed:@"iconfont-iconfontzanting"] forState:UIControlStateNormal];
    }
    [[LYRadioHelper shareLYRadioHelper] playOrPause];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.allTingList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YPSongTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YPSongTableCell" forIndexPath:indexPath];
     RadioDetailListModel *model  = self.allTingList[indexPath.row];
    cell.titleLable.text = model.title;
    cell.byLable.text = model.authorinfo.uname;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.currentIndex = indexPath.row;
   [self makeCurrentSongModelByIndex:self.currentIndex];
}

- (void)leftAction:(UIBarButtonItem*)sender{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YPMoretingModel *more = self.currentModel.moreting[indexPath.row];
    YPSongCollectionCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:@"YPSongCollectionCell" forIndexPath:indexPath];
    [item.collectionImage sd_setImageWithURL:[NSURL URLWithString:more.coverimg] placeholderImage:[UIImage imageNamed:@"16"]];
    item.titleLable.backgroundColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.8];
    item.titleLable.text = more.title;
    return item;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.currentModel.moreting.count;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger index = self.mainScroll.contentOffset.x / self.view.width;
    for (int i = 0; i < 4; i++) {
        UIView *tempView = [self.view viewWithTag:i + 350];
        tempView.backgroundColor = [UIColor redColor];
        if (i == index) {
            tempView.backgroundColor = [UIColor yellowColor];
        }
    }
}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    [self.listTableView reloadData];
    [self.otherWorks reloadData];
    if (scrollView == self.mainScroll) {
        [self.hostImage sd_setImageWithURL:[NSURL URLWithString:self.currentModel.playInfo.authorinfo.icon] placeholderImage:[UIImage imageNamed:@"16"]];
        self.hostLable.text = self.currentModel.playInfo.authorinfo.uname;
        [self.userImage sd_setImageWithURL:[NSURL URLWithString:self.currentModel.playInfo.userinfo.icon] placeholderImage:[UIImage imageNamed:@"16"]];
        self.userLable.text = self.currentModel.playInfo.userinfo.uname;
        self.radioLable.text = self.currentModel.playInfo.authorinfo.uname;
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentIndex inSection:0];
        [self.listTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
    }
}

- (NSInteger)getCurrentSongIndexByTingID:(NSString *)tingID{
    NSInteger index = 0;
    for (NSInteger i = 0; i < self.allTingList.count; i++) {
        if ([tingID isEqualToString:[self.allTingList[i] tingId]]) {
            index = i;
            break;
        }
    }
    return index;
}

- (void)makeCurrentSongModelByIndex:(NSInteger)index{
    RadioDetailListModel *model = self.allTingList[index];
    [self makeCurentModelWith:model.tingid];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
}

- (NSMutableArray *)allTingList{
    if (_allTingList == nil) {
        _allTingList = [NSMutableArray array];
    }
    return _allTingList;
}

- (YPSongModel *)currentModel{
    if (_currentModel == nil) {
        _currentModel = [[YPSongModel alloc]init];
    }
    return _currentModel;
}
+ (instancetype)shareSongController{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        song = [[YPSongController alloc]init];
    });
    return song;
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
